<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\Loader;
use think\Session;

use app\index\model\UserRelated;
use app\index\model\TruckLocation;
use app\index\model\TruckInfo;
use app\index\model\OrderRelated;
use app\index\model\BaseInfo;
use app\index\model\DistributionPoint;



class Service extends Controller
{
    public function getmappoint()
    {
        $result=Db::table('distribution_point')->select();
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    public function getCompleted($index)
    {
        $result1 = Db::table('all_data')
        ->where('state', '=', 2)
        ->count();
        $result2 = Db::table('all_data')
        ->where('state', '=', 2)
        ->field('freightId,orderid,createdate,acceptdate,enddate,bourn,kilometre,coefficient')
        ->order('freightId desc')
        ->page($index, 50)
        ->select();
        
        $data = array(
            0 => $result1,
            1 => $result2
        );
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    public function queryByFreightId($index,$freightId)
    {
        $result1 = Db::table('all_data')
        ->where('state','=',2)
        ->where('freightId','like','%'.$freightId.'%')
        ->count();
        $result2 = Db::table('all_data')
        ->where('state','=',2)
        ->where('freightId','like','%'.$freightId.'%')
        ->field('freightId,orderid,createdate,acceptdate,enddate,bourn,kilometre,coefficient')
        ->page($index, 50)
        ->select();
        $data = array(
            0 => $result1,
            1 => $result2
        );
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    public function getDetailedInfo($freightId,$orderid)
    {
        $result = Db::table('all_data')
        ->where('state','=',2)
        ->where('freightId',$freightId)
        ->where('orderid',$orderid)
        ->field('customer,board,flute,format,area,oneofarea,numberofplies,volume,mark')
        ->select();
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
	public function getwaitdata()
    {
       // $result=Db::table('all_data')->where('state',1)->order('freightId desc')->select();
        // for($i=0;$i<count($result);$i++)
        // {
        //     $result=Db::table('all_data')->where('truckid',$result)->order('freightId desc')->select();
        // }
        $result = Db::query("SELECT * FROM all_data,all_user WHERE  all_data.state = 1 AND all_user.truckid=all_data.truckid");
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    public function getorderfind()
    {
        $freightId=Request::instance()->param('freightId');
        if(strlen($freightId)==9)
        {
            $result=Db::table('all_data')->where('freightId',$freightId)->where('state',1)->where('truckid','not null')->select();
            $ut = new Utiltool($result);
            return $ut->getpdata();
        }else
        {
            $result=Db::table('all_data')->where('freightId','like','%'.$freightId.'%')->where('state',1)->where('truckid','not null')->select();
            $ut = new Utiltool($result);
            return $ut->getpdata();
        }
    }
    public function cancelorder()
    {
        $freightId=Request::instance()->param('freightId');
        //$orderid=Request::instance()->param('orderid');
        $mark=Request::instance()->param('mark');
        $canceldate=date('y-m-d H:i:s',time());
        $resulttruckid=Db::table('all_data')->where('freightId',$freightId)->field('truckid')->find();
        //$result=Db::table('all_data')->where('freightId',$freightId)->where('orderid',$orderid)->update(['state' => -1,'mark' =>$mark,'canceldate' =>$canceldate]);
        //$result=Db::table('all_data')->where('freightId',$freightId)->where('orderid',$orderid)->update(['state' => -1,'mark' =>$mark,'canceldate' =>$canceldate]);
        $result=Db::execute("UPDATE all_data,all_user 
        SET all_data.state =-1,all_data.canceldate = '".$canceldate."' ,all_user.state =0  
        WHERE all_user.truckid = '".$resulttruckid['truckid']."' AND all_data.truckid = '".$resulttruckid['truckid']."' AND all_data.freightId= '".$freightId."' AND all_data.state = 1");

        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    // CAt
    public function getTruckAtMap(){
        $TruckLocation = Db::query("
            SELECT all_user.truckid,longitude,latitude
            FROM truck_position,all_user
            WHERE all_user.state = 1
            AND truck_position.truckid = all_user.truckid
        ");
        $ut = new Utiltool($TruckLocation);
        return $ut->getpdata();
    }
    public function getBournAtMap(){
        $DistributionPoint = DistributionPoint::all();
        $ut = new Utiltool($DistributionPoint);
        return $ut->getpdata();
    }
    public function getOrderIdByTruckId(){
        $truckid = Request::instance()->param('truckid');
        $freightId = Db::table("all_data")->where("truckid",$truckid)->where("state",1)->column("freightid");
        $name = Db::table("all_user")->where("truckid",$truckid)->field("name,phone")->find();
        $result = array(
            // 送货点数量
            0 => Db::query("SELECT count(DISTINCT bourn) AS sum FROM all_data WHERE truckid = '$truckid'"),
            // 送货次数
            1 => Db::query("SELECT count(bourn) AS sum FROM all_data WHERE truckid = '$truckid'")
        );
        if(!$freightId){
            $freightId[0] = "当前没有运送货物";
        }
        $ut = new Utiltool([
            'freightId' => $freightId[0],                
            'name' => $name["name"],
            'phone' => $name["phone"],
            'dnum' => $result[0][0]['sum'],
            'num' => $result[1][0]['sum']
        ]);
        return $ut->getpdata();
    }
    public function getTruckIdByTruckId(){
        $truckid = Request::instance()->param('truckid');
        $TruckId = Db::table("all_user")
        ->where("truckid","like","%".$truckid."%")
        ->column("truckid");
        if($TruckId){
            $ut = new Utiltool($TruckId);
            return $ut->getpdata();
        }else{
             $ut = new Utiltool(['好像没有这个']);
            return $ut->getpdata();
        }
    }
    public function getOneTruckAtMap()
    {
        $truckid = Request::instance()->param('truckid');
        $TruckLocation =  Db::table("truck_position")
        ->where("truckid",$truckid)
        ->where('longitude','not null')
        ->field("truckid,longitude,latitude")
        ->find();
        $ut = new Utiltool($TruckLocation);
        return $ut->getpdata();
    }
    public function getSendingbournByTruckid()
    {
        $truckid = Request::instance()->param('truckid');
        $bourns = Db::query("SELECT bournname,longitude,latitude,total 
        FROM distribution_point,all_data
        WHERE all_data.bourn = distribution_point.bournname
        AND all_data.state = 1
        AND truckid = '$truckid'
        ");
        $ut = new Utiltool($bourns);
        return $ut->getpdata();
    }
    /**
     * Author:stardotdot
     */
    public function getUncompleteData()
    {
        $result=Db::table('all_data')->where('state',-1)->order("freightId desc")->select();
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    /**
    *Author:stardotdot
    */
    public function changeToWaitOrder()
    {
        $data=Request::instance()->param('data');
        $result=Db::table('all_data')->where('freightId',$data)->update(['state' => 0]);
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    /**
     * Author:stardotdot
     */
    public function getACancelOrder()
    {
        $data=Request::instance()->param('data');
        if(strlen($data)==9)
        {
            $result=Db::table('all_data')->where('freightId',$data)->where('state',-1)->order("freightId desc")->select();
            $ut = new Utiltool($result);
            return $ut->getpdata();
        }else
        {
            $result=Db::table('all_data')->where('freightId','like','%'.$data.'%')->where('state',-1)->order("freightId desc")->select();
            $ut = new Utiltool($result);
            return $ut->getpdata();
        }
    }
    public function getCreateDateByTruckid(){
        $truckid=Request::instance()->param();
        $data = Db::table("all_data")->distinct(true)->
                where($truckid)->
                field('createdate')
                ->select();
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    public function getOneDayByTurckIdAndDate(){
        $where = Request::instance()->post();
        // $data = Db::table("all_data")->
        //         where($where)->
        //         field('customer,bourn,board,flute,format,area,volume,truckload,coefficient,kilometre')
        //         ->select();
        $sql = "SELECT freightId,customer,bourn,board,flute,format,area,volume,truckload,coefficient,kilometre,longitude,latitude
                FROM all_data,distribution_point
                WHERE truckid = '".$where['truckid']."' AND createdate = '".$where['createdate']."'
                AND all_data.bourn = distribution_point.bournname";
        $data = Db::query($sql);
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    public function getOrderByTruckid(){
        $truckid=Request::instance()->param();
        $data = Db::table("all_data")->
                where($truckid)->
                field('customer,bourn,board,flute,format,area,volume,truckload,coefficient,kilometre')
                ->find();
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    public function getBournOrderNumByName(){
        $bourn = Request::instance()->post();
        $data = Db::table("all_data")->where($bourn)->count('bourn');
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    public function getOrderBySum()
    {
        $result = Db::query("SELECT all_data.truckid,all_user.truckid,all_user.name,COUNT(all_data.truckid) AS sum 
            FROM all_data,all_user
            WHERE all_data.truckid=all_user.truckid 
            GROUP BY all_data.truckid,all_user.name
            ORDER BY sum DESC");
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    public function getAllBournOrderNum(){
        $data = Db::query("SELECT bourn, COUNT(bourn) AS num FROM all_data GROUP BY bourn Order BY num DESC");
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    public function getWaitdataByFreightId(){
        $freightId = Request::instance()->param();
        $data = Db::table("all_data")->
                where($freightId)->
                field('customer,bourn,board,flute,format,area,oneofarea,numberofplies,width,length,volume,truckload,coefficient,kilometre')
                ->find();
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    public function getSumVolume(){
        $data = Db::query("SELECT freightId,truckid,SUM(volume) AS volume FROM all_data WHERE createdate LIKE '2017%' GROUP BY freightId,truckid");
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    public function getCustomerList(){
        $customer = Request::instance()->post('customer');
        $customers = Db::table("all_data")->distinct(true)->where('customer','like','%'.$customer.'%')->column("customer");
        $ut = new Utiltool($customers);
        return $ut->getpdata();
    }
    public function getBournList(){
        $bourn = Request::instance()->param('bourn');
        $bourns = Db::table("all_data")->distinct(true)->where('bourn','like','%'.$bourn.'%')->column("bourn");
        $ut = new Utiltool($bourns);
        return $ut->getpdata();
    }
    public function getNewList(){
        $data = Db::query("SELECT createdate,orderid,customer,bourn,board,flute,format,area,oneofarea,coefficient,numberofplies,volume,truckload FROM all_data ORDER BY createdate DESC LIMIT 1");
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
    public function getboardList(){
        $board = Request::instance()->param('board');
        $boards = Db::table("all_data")->distinct(true)->where('board','like','%'.$board.'%')->column("board");
        $ut = new Utiltool($boards);
        return $ut->getpdata();
    }
    public function getFluteList(){
        $flute = Request::instance()->param('flute');
        $flutes = Db::table("all_data")->distinct(true)->where('flute','like','%'.$flute.'%')->column("flute");
        $ut = new Utiltool($flutes);
        return $ut->getpdata();
    }
    public function getOrderList(){
        $order = Request::instance()->param('orderid');
        $orders = Db::table("all_data")->distinct(true)->where('orderid','like',$order.'%')->order('orderid')->column("orderid");
        $ut = new Utiltool($orders);
        return $ut->getpdata();
    }
    public function getFormatList(){
        $format = Request::instance()->param('format');
        $formats = Db::table("all_data")->distinct(true)->where('format','like','%'.$format.'%')->column("format");
        $ut = new Utiltool($formats);
        return $ut->getpdata();
    }
    //hardingCheng
    public function getYearData(){
        $data = Db::query(" SELECT DISTINCT year(createdate) as year FROM all_data where year(createdate) IS NOT NULL ORDER BY year");
        $ut = new Utiltool($data);
        return $ut->getpdata();
    }
     //hardingCheng
    public function getMonthlyTotalData(){
        $year=Request::instance()->param('year');
        $month=Request::instance()->param('month');
        if($month!='null'){
            $data = Db::query("SELECT createdate,COUNT(id) as total,SUM(volume) as volume
            FROM all_data
            WHERE createdate LIKE  '".$year.'-'.$month.'%'."' and state = 2
            GROUP BY createdate");
            $ut = new Utiltool($data);
            return $ut->getpdata();
        }else{
        $monthly=1;
        $datasum=array();
        for($monthly;$monthly<=12;$monthly++)
        {
            if($monthly>=1&&$monthly<=9)
            {
                $monthly="0".$monthly;
            }
            $data = Db::query("SELECT  DISTINCT month(bb) as month,SUM(aa) as total,SUM(volume) as volume
            FROM(
            SELECT createdate as bb,COUNT(id) as aa,SUM(volume) as volume
            FROM all_data
            WHERE createdate   LIKE '".$year.'-'.$monthly.'%'."' and state = 2
            GROUP BY createdate
            )
            as datatotal
            GROUP BY month");
            $datasum=array_merge($datasum,$data);
            }
            $ut = new Utiltool($datasum);
            return $ut->getpdata();
        }
    }
    //hardingCheng
    // public function getMonthlyVolumeTotal(){
    //     $year=Request::instance()->param('year');
    //     $month=Request::instance()->param('month');
    //     if($month!='null'){
    //         $data = Db::query("SELECT createdate,SUM(volume) as total
    //         FROM all_data
    //         WHERE createdate LIKE  '".$year.'-'.$month.'%'."'
    //         GROUP BY createdate");
    //         $ut = new Utiltool($data);
    //         return $ut->getpdata();
    //     }else{
    //     $monthly=1;
    //     $datasum=array();
    //     for($monthly;$monthly<=12;$monthly++)
    //     {
    //         if($monthly>=1&&$monthly<=9)
    //         {
    //             $monthly="0".$monthly;
    //         }
    //         $data = Db::query("SELECT  DISTINCT month(bb) as month,SUM(aa) as total
    //         FROM(
    //         SELECT createdate as bb,SUM(volume) as aa
    //         FROM all_data
    //         WHERE createdate   LIKE '".$year.'-'.$monthly.'%'."'
    //         GROUP BY createdate
    //         )
    //         as datatotal
    //         GROUP BY month");
    //         $datasum=array_merge($datasum,$data);
    //         }
    //         $ut = new Utiltool($datasum);
    //         return $ut->getpdata();
    //     }
    // }
    //hardingCheng
    // public function getWeekTotalData(){
    //     $year=Request::instance()->param('year');
    //     $month=Request::instance()->param('month');
    //     $datatotal=0;
    //     $volume=0;
    //     if($month!='null'){
    //         $result = Db::query("SELECT createdate,COUNT(freightId) as total,SUM(volume) as volume
    //         FROM all_data
    //         WHERE createdate LIKE  '".$year.'-'.$month.'%'."'
    //         GROUP BY createdate");
    //     }else{
    //         $result = Db::query("SELECT createdate,COUNT(freightId) as total,SUM(volume) as volume
    //         FROM all_data
    //         WHERE createdate LIKE  '".$year.'%'."'
    //         GROUP BY createdate");
    //     }
    //     for($i=0;$i<count($result);$i++)
    //     {
    //         $week=date('W',strtotime($result[$i]['createdate']));
    //         $result[$i]['week']=$week;
    //     }
    //     $yearweek=date("W", mktime(0, 0, 0, 12, 31, $year));
    //     if($yearweek=='01')
    //     {
    //         $yearweek=date("W", mktime(0, 0, 0, 12, 30, $year));
    //     }
    //     $data=array();
    //     for($i=1;$i<=$yearweek;$i++)
    //     {
    //         for($j=0;$j<count($result);$j++)
    //         {
    //             if((int)$result[$j]['week']==$i)
    //             {
    //                 $datatotal+=$result[$j]['total'];
    //                 $volume+=$result[$j]['volume'];
    //             }
    //         }
    //         $data[$i]['week']=$i;
    //         $data[$i]['total']=$datatotal;
    //         $data[$i]['volume']=$volume;
    //         $datatotal=0;
    //         $volume=0;
    //     }
    //     if($month!='null')
    //     {
    //         $monthweek=1;
    //         foreach( $data as $k=>$v) {
    //             if($data[$k]['total'] == 0) unset($data[$k]);
    //         }
    //         foreach( $data as $k=>$v) {
    //             $data[$k]['monthweek']=$monthweek;
    //             $monthweek++;
    //         }
    //     }
    //     $ut = new Utiltool($data);
    //     return $ut->getpdata();
    // }
    //hardingCheng
    public function getBournTruckCount()
    {
        Db::query("delete  from truck_bourn");
        Db::query("INSERT INTO  truck_bourn
        (
            bourn,truckid,frequency
        )
        SELECT  bourn,truckid,COUNT(truckid) as frequency FROM all_data WHERE  bourn IS NOT NULL AND  LENGTH(truckid) >= 9
        GROUP BY bourn,truckid");
    }
    // Cat 
    public function AddOrder(){
        $orderInfo = Request::instance()->post();
        $orderInfo["createdate"] = date("y-m-d");
        $orderInfo["state"] = 3;
        $result=Db::table("all_data")->insert($orderInfo);
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    // CAT
    public function getTBDOrder(){
        $result = Db::table("all_data")
        ->where("state","3")
        ->field('id,orderid,customer,bourn,board,flute,format,area,oneofarea,numberofplies,volume,truckload,coefficient')
        ->order('orderid desc')
        ->select();
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    // CAT
    public function splitOrder(){
        $orderInfo = Request::instance()->post();
        $result2=Db::table("all_data")->where("id",$orderInfo["oldId"])->delete();
        $orderInfo["afterData"]["createdate"] = date("y-m-d");
        $orderInfo["afterData"]["orderid"] = substr(date("YmdHi"),2);
        $orderInfo["afterData"]["state"] = 3;
        $result=Db::table("all_data")->insert($orderInfo["afterData"]);
        $orderInfo["nowData"]["createdate"] = date("y-m-d");
        $orderInfo["nowData"]["orderid"] = substr(date("YmdHi"),2);
        $orderInfo["nowData"]["state"] = 3;
        $result1=Db::table("all_data")->insert($orderInfo["nowData"]);
        if($result&&$result1&&$result2){  
            $ut = new Utiltool(1);
            return $ut->getpdata();
        }else{
            $ut = new Utiltool(0);
            return $ut->getpdata();
        }
    }
    //aye
    public function produceFreightId(){
        $combineId = Request::instance()->post();
        $begin="A";
        $date=date("ymd");
        $rand= Db::table('all_data')->where('freightId','<>','')->order('freightId desc')->limit(2)->column("freightId");
        if(substr($rand[0],5,2) === substr($rand[1],5,2)){
            $rand = (int)substr($rand[0],7,2)+1;
            if($rand < 10){
                $freightId=$begin.$date.'0'.$rand;
            }else{
                $freightId=$begin.$date.$rand;
            }
        }else{
            $freightId=$begin.$date.'01';
        }
        //订单号暂时就这样随机
        $str = $combineId["mergeId"];
        $acceptdate = date("Y/m/d h:i:s");
        $flag = 0;
        for($i=0;$i<count($str);$i++){
           $change=$str[$i];
           if(array_key_exists("truckid",$combineId)){
            if($combineId["truckid"] != ""){
                    $truckid = $combineId["truckid"];
                    $data = Db::execute("UPDATE all_user set state = 1 WHERE truckid = '$truckid'");
                    if($combineId["isEmergency"]){
                        $data = Db::execute("UPDATE all_data set freightId ='$freightId' , truckid = '$truckid' , state = '1' , isEmergency = '1' , acceptdate = '$acceptdate'  WHERE id=$change ");  
                    }else{
                        $data = Db::execute("UPDATE all_data set freightId ='$freightId' , truckid = '$truckid' , state = '1' , isEmergency = '0' , acceptdate = '$acceptdate'  WHERE id=$change");
                    }
            }else{
                    if($combineId["isEmergency"]){
                        $data = Db::execute("UPDATE all_data set freightId ='$freightId' , state = '4' , isEmergency = '1'  WHERE id=$change ");
                    }else{
                        $data = Db::execute("UPDATE all_data set freightId ='$freightId' , state = '4' , isEmergency = '0'  WHERE id=$change");
                    }
            }
           }else{
                $data = Db::execute("UPDATE all_data set freightId ='$freightId' , state = '4' , isEmergency = '0'  WHERE id=$change ");
                
           }
           if(!$data){
                $flag = $i;
           }
        }
        if(!$flag){  
            $ut = new Utiltool($freightId);
            return $ut->getpdata();
        }else{
            $ut = new Utiltool(0);
            return $ut->getpdata();
        }
    }
    public function get_kmeans_mouth(){
        header("Content-type:text/html; charset=utf-8");
        $mouth = Request::instance()->post();
        // var_dump($mouth);
        // $select_mouth = $mouth['mouth'];
        // $date = $mouth['date'];
        $date="2016-10-01";
        $select_mouth="10";
        $set_charset = 'export LANG=en_US.UTF-8;';
        if(1){
            $comp_date = "2016-10-01";
        }
        else{
            $comp_date = $mouth['comp_date'];
        }
        exec("python static/python/mouth_comp.py  2>python_error.txt $select_mouth $date $comp_date",$Array,$ret);
        $ut = new Utiltool($Array);
        return $ut->getpdata();
        // return $Array;
    }
    //aye
    public function changePassword(){
        $pw=Request::instance()->post('pw');
        $newpw=Request::instance()->post('newpw');
        $telephone=Request::instance()->post('telephone');
        $changepw = Db::execute("UPDATE user SET password ='$newpw' WHERE telephone='$telephone' and password='$pw'");
        $ut = new Utiltool($changepw);
        return $ut->getpdata();
    }
    //aye
    public function bournManage($index){
       
        $bournManage = Db::query("SELECT * FROM distribution_point");
        $bournManagePages = Db::table('distribution_point')
        ->order('total','desc')
        ->page($index, 50)
        ->select();
        $bournManageCount = Db::table('distribution_point')->count();
        $wholedata = array(
            0 => $bournManage,
            1 => $bournManagePages,
            3 => $bournManageCount
        );
        $ut = new Utiltool($wholedata);
        return $ut->getpdata();
    }
    //aye
    public function queryBournManage(){
        $selectType = Request::instance()->post('bournid');
        $slectSql=Db::query("SELECT * from distribution_point WHERE bournid LIKE '%$selectType%' OR bournname LIKE '%$selectType%'");
        $ut = new Utiltool($slectSql);
        return $ut->getpdata();
    }
   
    //aye（周六周日的送车量sql查询暂不用）
    public function getWeekendInfo()
    {
        $WeekendInfo = Db::query("SELECT truckid ,DAYOFWEEK(createdate) as my,COUNT(DAYOFWEEK(createdate)) 
        from all_data  WHERE length(truckid)>8
        GROUP BY truckid,my
        HAVING my = '1' or my = '7'"); 
        $SaturdayAndSun = array(); 
        for ($i=0,$j=1; $i <count($WeekendInfo); $i+=2,$j+=2) { 
            $data['truckid']=$WeekendInfo[$i]['truckid'];
            $data['Saturday']=$WeekendInfo[$i]['COUNT(DAYOFWEEK(createdate))'];
            $data['Sunday']=$WeekendInfo[$j]['COUNT(DAYOFWEEK(createdate))'];
            $data['frequency']=$data['Saturday']+$data['Sunday'];
            array_push($SaturdayAndSun,$data);
        }
        Db::table('truck_week')->delete(true);
        Db::name('truck_week')->insertAll($SaturdayAndSun);  
    }
    // CAT
    public function getTruckList(){
        $truckList = Db::query("SELECT all_user.truckid,Saturday,Sunday,frequency,volume 
        FROM truck_week,vehicle_load,all_user 
        WHERE truck_week.truckid = vehicle_load.licensePlate
        AND all_user.truckid = truck_week.truckid
        AND vehicle_load.licensePlate = all_user.truckid
        AND all_user.singlestate = 1
        AND all_user.state = 0
        ");
        $ut = new Utiltool($truckList);
        return $ut->getpdata();
    }
    // Cat
    public function produceTruckId(){
        $truckid = Request::instance()->post("truckid");
        $freightId = Request::instance()->post("freightId");
        $result = Db::table('all_data')->where('freightId', $freightId)->update(['truckid' => $truckid]);
        if($result){  
            $ut = new Utiltool(1);
            return $ut->getpdata();
        }else{
            $ut = new Utiltool(0);
            return $ut->getpdata();
        }
    }
    // Cat
    public function getOneInfoByOrderid(){
        $orderid = Request::instance()->param("orderid");
        $result = Db::table("all_data")->where("orderid",$orderid)
        ->field('id,orderid,customer,bourn,board,flute,format,area,oneofarea,numberofplies,volume,truckload,coefficient')->find();
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    // Cat
    public function login(){
         $userInfo = Request::instance()->post();
        $validate = Loader::validate('Modeluser');
        if(!$validate->check($userInfo)){
            $ut = new Utiltool(null);
            return $ut->getpdata();
        }
        $result = Db::table("user")
        ->where("telephone",$userInfo["phone"])
        ->where("password",md5($userInfo["password"]))
        ->field("username,job")
        ->find();
        Session::set('isLog',$result);
        if(!$result){
            $ut = new Utiltool(null);
            return $ut->getpdata();
        }
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    // Cat
    public function getFactory(){
        $result = Db::table("factory_location")
        ->select();
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    public function getPhoneByPhone(){
        $phone = Request::instance()->param("phone");
        $userInfo = Db::table("all_user")
        ->where("phone","like","%".$phone."%")
        ->column("phone");
        if($userInfo){
            $ut = new Utiltool($userInfo);
            return $ut->getpdata();
        }else{
            $ut = new Utiltool(['好像没有这个']);
            return $ut->getpdata();
        }
    }
    // wz
    public function download()
    {
        header('Content-type: application/force-download');
        header('Content-Disposition: attachment; filename="帮助文档v1.0.zip"');   
        @readfile('http://172.17.130.151:8080/YF/Public/static/帮助文档v1.0.zip');
    }
    public function getAllUser()
    {
        $result = Db::query("SELECT truckid,name,phone,identity,age,sex,lastdate
            FROM all_user ORDER BY lastdate DESC");
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    public function getSearchTruck($phone)
    {
        $result = Db::query("SELECT truckid,name,phone,identity,age,sex
            FROM all_user
            WHERE phone LIKE '%$phone%'
            ORDER BY userid DESC");
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    public  function addFactory(){
        $info =  Request::instance()->post();
        $result = Db::table('factory_location')->insert($info);
        if(!$result){
            $ut = new Utiltool(null);
            return $ut->getpdata();
        }
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    public function deleteFactory(){
        $info =  Request::instance()->post();
        $result = Db::table('factory_location')->where($info)->delete();
        if(!$result){
            $ut = new Utiltool(null);
           return $ut->getpdata();
       }
    }
    public function addUser()
    {
        $user = Request::instance()->post();
        $user['password'] = md5($user['password']);
        $result = Db::table('all_user')->insert($user);
        $result_vehicle_load=['licensePlate'=>$user['truckid'],'volume'=>null,'owner'=>null,'phone'=>$user['phone']];
        $result_truck_week=['truckid'=>$user['truckid'],'Sunday'=>null,'Saturday'=>null,'frequency'=>null];
        $result_truck_position=['truckid'=>$user['truckid'],'longitude'=>null,'latitude'=>null,'positiontime'=>null];
        $result_vehicle_load1=Db::table('vehicle_load')->insert($result_vehicle_load);
        $result_truck_week1=Db::table('truck_week')->insert($result_truck_week);
        $result_truck_position1=Db::table('truck_position')->insert($result_truck_position);
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    public function deleteUser()
    {
        $parameter = Request::instance()->post();
        $result = Db::table("all_user")->where('truckid',$parameter['truckid'])->delete();
        $result2 = Db::table("vehicle_load")->where('licensePlate',$parameter['truckid'])->delete();
        $result3 = Db::table("truck_week")->where('truckid',$parameter['truckid'])->delete();
        $result1 = Db::table("truck_position")->where('truckid',$parameter['truckid'])->delete();
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    public function updateUser()
    {
        $data = Request::instance()->post();
        $result = Db::table("all_user")
                    ->where('phone', $data['phone'])
                    ->update([
                        'name' => $data['name'],
                        'username' => $data['username'],
                        'truckid' => $data['truckid'],
                        'identity' => $data['identity'],
                        'age' => $data['age'],
                        'sex' => $data['sex']
                    ]);
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    public function removeFreight($freightId)
    {

        $result = Db::table("all_data")
                    ->where('freightId', $freightId)
                    ->where('state', '-1')
                    ->update([
                        'state' => '3',
                        'truckid' => '',
                        'freightId' => '',
                        'mark' => '',
                        'acceptdate' => null,
                        'enddate' => null,
                        'canceldate' => null
                    ]);
        $ut = new Utiltool($result);
        return $ut->getpdata();
    }
    /**
     * 运单量热力图
     */
    public function getHotMaps(){
        $start_time=Request::instance()->param("start_time");
        $end_time=Request::instance()->param("end_time");
        // $result=Db::query("select all_data.bourn,count(*) as count,distribution_point.longitude,distribution_point.latitude
        // from all_data,distribution_point where createdate between '2016-01-01' and '2016-12-31' and
        // all_data.bourn=distribution_point.bournname group by bourn,distribution_point.longitude,distribution_point.latitude
        // ");
        // var_dump($result);
        $result=Db::query("select bourn,count(*) as count from all_data where createdate between '$start_time' and '$end_time' group by bourn");
        // var_dump($result);
        $data=Db::table('distribution_point')->field('bournname,longitude,latitude')->
        where('longitude','not null')->where('latitude','not null')->select();
        // var_dump($data);
        $res=array();
        for($i=0;$i<count($result);$i++){
            for($j=0;$j<count($data);$j++){
                if($result[$i]['bourn']==$data[$j]['bournname']){
                    $arr=array();
                    // $arr['bourn']=$result[$i]['bourn'];
                    $arr['lng']=$data[$j]['longitude'];
                    $arr['lat']=$data[$j]['latitude'];
                    
                    $arr['count']=$result[$i]['count'];
                   
                    array_push($res,$arr);
                }
               
            }
        }
        // var_dump($res);
        $ut = new Utiltool($res);
        return $ut->getpdata();

    }
    /**
     * 车次
     */
    public function getCarCountHotMaps(){
        $start_time=Request::instance()->param("start_time");
        $end_time=Request::instance()->param("end_time");
        $result = Db::table('all_data')
        ->Distinct(true)
        ->field('truckid,bourn,createdate')
        ->where('createdate','between',[$start_time,$end_time])
        ->select();
       
    
        // for($i=1;$i<count($result);$i++){
        //     in_array($result[$i],$a)?null:array_push($a,$result[$i]);
        // }
        foreach($result as $key=>$value){
            $arr[$value['bourn']][] = $value;
        }
        $CarData=array();
        foreach($arr as $key=>$value){
            if($key!=''){
           array_push($CarData,array('bourn'=>$key,'count'=>count($arr[$key])));
            }
        }
        // var_dump($CarData);
        $data=Db::table('distribution_point')->field('bournname,longitude,latitude')->
        where('longitude','not null')->where('latitude','not null')->select();
        $res=array();
        for($i=0;$i<count($CarData);$i++){
            for($j=0;$j<count($data);$j++){
                if($CarData[$i]['bourn']==$data[$j]['bournname']){
                    $arr=array();
                    // $arr['bourn']=$result[$i]['bourn'];
                    $arr['lng']=$data[$j]['longitude'];
                    $arr['lat']=$data[$j]['latitude'];
                    
                    $arr['count']=$CarData[$i]['count'];
                   
                    array_push($res,$arr);
                }
               
            }
        }
        // var_dump($res);
        $ut = new Utiltool($res);
        return $ut->getpdata();

    }
    /**
     * 更新函数--NO接口
     */
    public function update(){
        $result=Db::query("select bourn,count(*) as count from all_data  group by bourn");
        $data=Db::table('distribution_point_copy')->field('bournname,longitude,latitude')->
        where('longitude','not null')->where('latitude','not null')->select();
        $res=array();
        for($i=0;$i<count($result);$i++){
            for($j=0;$j<count($data);$j++){
                if($result[$i]['bourn']==$data[$j]['bournname']){

                    $bourn=$result[$i]['bourn'];
                    $count=$result[$i]['count'];
                    $sql='update distribution_point_copy set total= '.$count.' WHERE bournname="'.$bourn.'"';
                    // echo $sql;
                    // var_dump($sql);
                    $success=Db::execute($sql);
                }
               
            }
        }
    }
    /**
     * python-聚类接口-聚类中心
     */
    public function getClustersPy(){
        // $start_time = '2016-1-01';
        // $end_time = '2016-3-31';
        $start_time=Request::instance()->param("start_time");
        $end_time=Request::instance()->param("end_time");
        $center_count=Request::instance()->param("center_count");
	//var_dump($start_time);        
	//var_dump($center_count);
	$center_count=3;
	exec("/usr/local/python3/bin/python3 /usr/share/nginx/shareCup/YF/public/static/python/db.py  2>python_error.txt $start_time $end_time $center_count",$Array,$ret);
       var_dump($Array);
        $data_array=array();
        for($i = 0;$i<count($Array);$i++){
            $arr=array();
            $arr['lng']=$Array[$i];
            $arr['lat']=$Array[++$i];
            array_push($data_array,$arr);
        }
        // var_dump($data_array);
        $ut = new Utiltool($data_array);
        return $ut->getpdata();
    }
    /**
     * 绘制单个聚类图
     */
    public function getOnlyClusterData(){
        $start_time=Request::instance()->param("start_time");
        $end_time=Request::instance()->param("end_time");
        $center_count=Request::instance()->param("center_count");
        // $start_time='2016-01-01';
         //$end_time='2016-12-28';
        // $center_count=3;
        // var_dump($start_time);
        $result_1=Db::query("select DISTINCT bourn from all_data where createdate between '$start_time' and '$end_time'");
        $result_2=Db::table('distribution_point')->field('bournname,longitude,latitude')->
        where('longitude','not null')->where('latitude','not null')->select();
        $res=array();
        for($i=0;$i<count($result_1);$i++){
            for($j=0;$j<count($result_2);$j++){
                if($result_1[$i]['bourn']==$result_2[$j]['bournname']){
                    $arr=array();
                    // $arr['bourn']=$result[$i]['bourn'];
                    $arr[0]=$result_2[$j]['longitude'];
                    $arr[1]=$result_2[$j]['latitude'];                    
                    array_push($res,$arr);
                }   
            }
        }
	//var_dump($res);
      exec("/usr/local/python3/bin/python3 /usr/share/nginx/shareCup/YF/public/static/python/db.py 2>python_error.txt $start_time $end_time $center_count",$Array,$ret);
       // var_dump($Array);
        $data_array=array();
        for($i = 0;$i<count($Array);$i++){
            $arr=array();
            $arr['lng']=$Array[$i];
            $arr['lat']=$Array[++$i];
            array_push($data_array,$arr);
        }
        
        for($i=0;$i<$center_count;$i++){
            $cluster_arr[$i]=array();
        }
        for($i=0;$i<count($res);$i++){
            $dis_arr=array();
            for($j=0;$j<count($data_array);$j++){
                $d=$this->getDistance($res[$i][0],$res[$i][1],$data_array[$j]['lng'],$data_array[$j]['lat']);
                array_push($dis_arr,$d);
            }
            $key = array_search(min($dis_arr),$dis_arr); 
            // var_dump($key);
            array_push($cluster_arr[$key],$res[$i]);

        }
        $result_data=array();
        array_push($result_data,$data_array);
        array_push($result_data,$cluster_arr);
        // var_dump($result_data);
        $ut = new Utiltool($result_data);
        return $ut->getpdata();
    }
    /**
     * 获取两点间距离
     * @param  $latitude1 纬度1
     * @param  $longitude1 经度1
     * @param  $longitude2 纬度2
     * @param  $latitude2 经度2
     * @return array
     */
    // function getDistance($lat1,$lng1,$lat2,$lng2)
    // {
    //     $ak = '9whTPxXrl8zvW3gjiAaoPa59gFekKK9I';
    //     $distance = array();
    //     $distance['distance'] = 0.00;//距离 公里
    //     $distance['duration'] = 0.00;//时间 分钟
    //     $url = 'http://api.map.baidu.com/routematrix/v2/driving?output=json&origins='.$lat1.','.$lng1.'&destinations='.$lat2.','.$lng2.'&ak='.$ak;
    //     $data = file_get_contents($url);
    //     $data = json_decode($data,true);
    //     if (!empty($data) && $data['status'] == 0) {
    //         $distance['distance'] =preg_replace('/[^\.0123456789]/s', '', $data['result'][0]['distance']['text']); //计算距离
    //     }
    //     return $distance;
    // }
    function getDistance($longitude1, $latitude1, $longitude2, $latitude2){

        $EARTH_RADIUS = 6370.996; // 地球半径系数
        $PI = 3.1415926;
    
        $radLat1 = $latitude1 * $PI / 180.0;
        $radLat2 = $latitude2 * $PI / 180.0;
    
        $radLng1 = $longitude1 * $PI / 180.0;
        $radLng2 = $longitude2 * $PI /180.0;
    
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
    
        $distance = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
        $distance = $distance * $EARTH_RADIUS ;//公里
    
        return  $distance;
    
    }

}
